package net.hailxenu.stats;

import java.io.File;
import java.io.FileWriter;
import java.net.*;

public class Server
{
    
    public static ServerSocket ss;
    private static SqlHandler sql;

    public static void main(String[] args)
    {
        try
        {
            Configuration SQLConfig = new Configuration(new File("server.properties"));
            if(!SQLConfig.hasKey("host") || !SQLConfig.hasKey("user") || !SQLConfig.hasKey("pass") || !SQLConfig.hasKey("database"))
            {
                FileWriter fw = new FileWriter(new File("server.properties"));
                fw.write("user: \npass: \nhost: \ndatabase: \n");
                fw.flush();
                fw.close();
                Logger.log(LT.CRITICAL, "No MySQL configuration detected. Please fill in the blank one that has been created.");
                System.exit(-1);
            }

            // SQL
            Logger.log(LT.INFO, "Establishing SQL Connection...");
            sql = new SqlHandler(SQLConfig.getString("host"), SQLConfig.getString("user"), SQLConfig.getString("pass"), SQLConfig.getString("database"));
            Logger.log(LT.INFO, "SQL Connection Successful");
            sql.write("UPDATE `servers_players` SET `online`=0;");
            sql.write("UPDATE `players` SET `online`=0;");

            // Server
            ss = new ServerSocket(25564);
            Logger.log(LT.INFO, "Server bound to port " + ss.getLocalPort());

            // Loop
            ClientHandler ch;
            while(!ss.isClosed())
            {
                new Thread(new ClientHandler(ss.accept(), sql)).start();
            }
        } catch(Exception e)
        {
            e.printStackTrace();
            Logger.log(LT.CRITICAL, "Server shutting down due to " + e.getMessage() + " ...");
        }
    }

    
}